import { useEffect, useState } from 'react'

import { isSSR } from '@/utils/is'

const getDefaultStorage = (key) => {
  if (!isSSR) {
    if (window.electron) {
      return window.electron.ipcRenderer.getStoreValue(key)
    }
    return localStorage.getItem(key)
  } else {
    return undefined
  }
}

function useStorage(key: string, defaultValue?: string): [string, (string) => void, () => void] {
  const [storedValue, setStoredValue] = useState(getDefaultStorage(key) || defaultValue)

  const setStorageValue = (value: string) => {
    if (!isSSR) {
      if (window.electron) {
        window.electron.ipcRenderer.setStoreValue(key, value)
      } else {
        localStorage.setItem(key, value)
      }
      if (value !== storedValue) {
        setStoredValue(value)
      }
    }
  }

  const removeStorage = () => {
    if (!isSSR) {
      if (window.electron) {
        window.electron.ipcRenderer.removeStoreValue(key)
      } else {
        localStorage.removeItem(key)
      }
    }
  }

  useEffect(() => {
    let storageValue
    if (window.electron) {
      storageValue = window.electron.ipcRenderer.getStoreValue(key)
    } else {
      storageValue = localStorage.getItem(key)
    }
    if (storageValue) {
      setStoredValue(storageValue)
    }
  }, [key])

  return [storedValue, setStorageValue, removeStorage]
}

export default useStorage
